<template>
  <div>
    <!-- 间距组件 -->
    <el-space>
      <!-- 激活-冻结 -->
      <el-select placeholder="请选择广告状态" v-model="status">
        <el-option label="激活" value="1" />
        <el-option label="冻结" value="0" />
      </el-select>
      <!-- 广告类型 -->
      <el-select placeholder="请选择广告类型" v-model="type">
        <el-option
          v-for="item in adTypeMap"
          :label="item.name"
          :value="item.value"
          :key="item.value"
        />
      </el-select>
      <el-button
        type="primary"
        class="iconfont icon-sousuo"
        @click="advertising()"
        >查找</el-button
      >
      <el-button type="primary" class="iconfont icon-tianjia" @click="add()"
        >添加</el-button
      >
    </el-space>
    <!-- 带边框的表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="广告ID" align="center" />
      <el-table-column prop="title" label="广告标题" align="center" />
      <el-table-column
        prop="imgUrl"
        label="广告图片"
        align="center"
        width="150px"
      >
        <template #default="scope">
          <el-popover
            width="500"
            placement="right"
            v-if="scope.row.type != 6 && scope.row.type != 9"
          >
            <template #reference>
              <el-image :src="scope.row.imgUrl" />
            </template>
            <img
              :src="scope.row.imgUrl"
              style="max-height: 200px; max-width: 300px"
            />
          </el-popover>
          <el-tag v-else type="info">此类型无需图片</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="广告类型" align="center">
        <template #default="scope">
          <el-tag>{{ advertisingtype(scope.row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="广告状态" align="center" width="90px">
        <template #default="scope">
          <el-tag :type="scope.row.status ? 'primary' : 'danger'">
            {{ scope.row.status == 1 ? "激活" : "冻结" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="unionType"
        label="关联类型"
        align="center"
        width="90px"
      >
        <template #default="scope">
          <el-tag type="danger">{{ show(scope.row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="unionValue" label="关联值[ID]" align="center" />
      <el-table-column
        prop="gmtCreate"
        label="创建时间"
        align="center"
        :formatter="dateFormat"
      />
      <el-table-column prop="name" label="操作" align="center">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加对话框 -->
    <el-dialog v-model="dialogVisible" title="添加" width="30%" @open="aikes">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="addFormRule"
        label-width="120px"
        
      >
        <el-form-item label="广告标题" prop="title">
          <el-input v-model.trim="ruleForm.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="广告类型" prop="type">
          <el-select placeholder="请选择" v-model="ruleForm.type" autocomplete="off">
            <el-option
              v-for="item in adTypeMap"
              :label="item.name"
              :value="item.value"
              :key="item.value"
            />
          </el-select>
        </el-form-item>
         <el-form-item
          label="广告图片"
          v-model="ruleForm.imgUrl"
          v-if="ruleForm.type <6&&ruleForm.type!=''"
          prop="imgUrl"
        >
          <el-upload
            class="avatar-uploader"
            action="http://192.168.1.188:8080/upload/admin"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="token"
          >
            <img v-if="ruleForm.imgUrl" :src="ruleForm.imgUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
          
        </el-form-item>

        <el-form-item label="广告状态">
          <el-switch
            v-model="ruleForm.status"
            class="ml-2"
            active-color="#13ce66"
            inactive-color="#ccc"
            :inactive-value="0"
            :active-value="1"
          />
        </el-form-item>
        <el-form-item label="类型关联" prop="unionType">
          <el-select
            placeholder="点击时跳转目标"
            v-model="ruleForm.unionType"
            :disabled="!ruleForm.type"
          >
            <el-option
              v-for="item in adUnionTypeMap"
              :label="item.name"
              :value="item.value"
              :key="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 商品 -->
        <el-form-item label="商品" v-if="ruleForm.unionType == 1" prop="unionValue">
          <el-config-provider :locale="locale">
            <div class="example-block">
              <el-cascader
                :options="options"
                :props="props1"
                clearable
                v-model="ruleForm.unionValue"
                placeholder="关联至商品"
              />
            </div>
          </el-config-provider>
        </el-form-item>
        <!-- 类目 -->
        <el-form-item label="类目" v-if="ruleForm.unionType == 2" prop="unionValue">
          <el-config-provider :locale="locale" label="类型关联">
            <div class="example-block">
              <el-cascader
                :options="optionss"
                :props="props2"
                clearable
                v-model="ruleForm.unionValue"
                placeholder="关联至类目"
              />
            </div>
          </el-config-provider>
        </el-form-item>
        <!-- 关键字 -->
        <el-form-item label="关键字" v-if="ruleForm.unionType == 3" prop="unionValue">
          <el-input
            placeholder="点击广告后用户将得到此关键字"
            v-model="ruleForm.unionValue"
          />
        </el-form-item>
        <!-- 功能页面 -->
        <el-form-item
          label="功能类型"
          prop="unionType"
          v-if="ruleForm.unionType == 4"
        >
          <el-select
            placeholder="请选择一个功能页面"
            v-model="ruleForm.unionValue"
          >
            <el-option
              v-for="ess in functionPages"
              :label="ess.name"
              :value="ess.value"
              :key="ess.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="sure('ruleFormRef')"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog
      v-model="dialogVisibles"
      title="编辑"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleFormRefs"
        :model="ruleForms"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="广告标题" prop="title">
          <el-input v-model.trim="ruleForms.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="广告类型" prop="type">
          <el-select placeholder="请选择" v-model="ruleForms.type">
            <el-option
              v-for="item in adTypeMap"
              :label="item.name"
              :value="item.value"
              :key="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="广告图片" v-if="ruleForms.type < 6">
          <el-upload
            class="avatar-uploader"
            action="http://192.168.1.188:8080/upload/admin"
            :show-file-list="false"
            :on-success="AvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="token"
          >
            <img
              class="avatar"
              :src="ruleForms.imgUrl"
              style="width: 80px; height: 80px"
            />
          </el-upload>
        </el-form-item>
        <el-form-item label="广告状态">
          <el-switch
            v-model="ruleForms.status"
            class="ml-2"
            active-color="#13ce66"
            inactive-color="#ccc"
            :inactive-value="0"
            :active-value="1"
          />
        </el-form-item>
        <el-form-item label="类型关联" prop="unionType">
          <el-select placeholder="点击时跳转目标" v-model="ruleForms.unionType">
            <el-option
              v-for="item in adUnionTypeMap"
              :label="item.name"
              :value="item.value"
              :key="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 商品 -->
        <el-form-item label="商品" v-if="ruleForms.unionType == 1">
          <el-config-provider :locale="locale">
            <div class="example-block">
              <el-cascader
                :options="options"
                :props="props1"
                clearable
                v-model="ruleForms.unionValue"
                placeholder="关联至商品"
              />
            </div>
          </el-config-provider>
        </el-form-item>
        <!-- 类目 -->
        <el-form-item label="类目" v-if="ruleForms.unionType == 2">
          <el-config-provider :locale="locale" label="类型关联">
            <div class="example-block">
              <el-cascader
                :options="optionss"
                :props="props2"
                clearable
                v-model="ruleForms.unionValue"
                placeholder="关联至类目"
              />
            </div>
          </el-config-provider>
        </el-form-item>
        <!-- 关键字 -->
        <el-form-item label="关键字" v-if="ruleForms.unionType == 3" >
          <el-input
            placeholder="点击广告后用户将得到此关键字"
            v-model="ruleForms.unionValue"
          />
        </el-form-item>
        <!-- 功能页面 -->
        <el-form-item
          label="功能类型"
          prop="unionType"
          v-if="ruleForms.unionType == 4"
        >
          <el-select
            placeholder="请选择一个功能页面"
            v-model="ruleForms.unionValue"
          >
            <el-option
              v-for="item in functionPages"
              :label="item.name"
              :value="item.value"
              :key="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editor('ruleFormRefs')">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分页 -->
    <PaginAtion
      class="dins"
      v-bind="paging"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    >
    </PaginAtion>
  </div>
</template>
<script>
  import { Plus } from "@element-plus/icons-vue";
  import cookin from "js-cookie";
  import zhCn from "element-plus/lib/locale/lang/zh-cn";
  import { ElConfigProvider } from "element-plus";
  import { ElMessage } from "element-plus";
  import PaginAtion from "@/Subassembly/PaginAtion";
  import moment from "moment";
  import http from "@/http";
  import host from "@/http";
  export default {
    components: {
      PaginAtion,
      ElConfigProvider,
    },
    data() {
      return {
        adId: "", //定义id
        dialogVisible: false, //创建弹出框
        dialogVisibles: false, //编辑弹出框
        locale: zhCn, //国际化中文
        value2: false,
        options: [], //接收类目
        //商品级联组件
        props1: {
          children: "children",
          label: "label",
          value: "id",
          checkStrictly: true,
          emitPath: false,
        },
        props2: {
          children: "childrenList",
          label: "title",
          value: "id",
          checkStrictly: true,
          emitPath: false,
        },
        //创建
        ruleForm: {
          type: "",
          unionType: "",
          title: "",
          imgUrl: "",
          status: 1,
          Color: "",
          unionValue: "",
        },
        // 编辑
        ruleForms: {
          type: "",
          unionType: "",
          title: "",
          imgUrl: "",
          status: "",
          Color: "",
          unionValue: "",
        },

        tableData: [],
        type: "",
        pageNo: "",
        limit: "",
        status: "",

        //正则
        addFormRule: {
          title: [
            {
              required: true,
              message: "广告标题不能为空！",
              trigger: "blur",
            },
          ],
          type: [
            {
              required: true,
              message: "广告类型不能为空！",
              trigger: "change",
            },
          ],
          unionValue:[
              {
              required: true,
              message: "此项不能为空！",
              trigger: "blur",
            },
          ]
        },
        rules : {           
          title: [
            {
              required: true,
              message: "广告标题不能为空！",
              trigger: "blur",
            },
          ],
          type: [
            {
              required: true,
              message: "广告类型不能为空！",
              trigger: "change",
            },
          ],
          unionValue:[
              {
              required: true,
              message: "此项不能为空！",
              trigger: "blur",
            },
          ]
        },
       
        adTypeMap: [
          {
            value: 1,
            unionTypes: [1, 2, 3, 4],
            picRequire: true,
            name: "轮播",
          },
          { value: 2, unionTypes: [2], picRequire: true, name: "分类精选" },
          {
            value: 3,
            unionTypes: [1, 2, 3, 4],
            picRequire: true,
            name: "横幅",
          },
          {
            value: 4,
            unionTypes: [1, 2, 3, 4],
            picRequire: true,
            name: "首页轮播下5按钮",
          },
          {
            value: 6,
            unionTypes: [1, 2, 3, 4],
            picRequire: false,
            name: "公告",
          },
          { value: 9, unionTypes: [1], picRequire: false, name: "商品推荐" },
        ],
        //4种广告关联类型
        adUnionTypeMap: [
          { value: 1, name: "商品" },
          { value: 2, name: "类目" },
          { value: 3, name: "关键字" },
          { value: 4, name: "功能页面" },
        ],
        //广告状态
        adStatusMap: [
          { value: 0, name: "冻结" },
          { value: 1, name: "激活" },
        ],
        //功能页面
        functionPages: [
          { value: "/pages/product/groupshop", name: "团购列表" },
          { value: "/pages/couponst", name: "优惠券列表" },
        ],
        //分页a
        paging: {
          page: 1, //默认第一页
          limit: 10, //显示一行几页
          total: "", //总页
        },
      };
    },
    created() {
      this.advertising();
      this.category();
      this.dows();
      this.token = {
        AdminToken: cookin.get("token"),
      };
    },
    methods: {
      //渲染数据
      advertising() {
        let data = {
          _gp: "admin.advert",
          _mt: "list",
          type: this.type,
          pageNo: this.paging.page,
          limit: this.paging.limit,
          status: this.status,
        };
        http.post(data).then((res) => {
          console.log(res);
          if (200 == res.errno) {
            this.tableData = res.data.items;
            this.paging.total = res.data.total;
          }
        });
      },
      //类目树
      category() {
        let leimu = {
          _gp: "admin.category",
          _mt: "categoryTree",
        };
        http.post(leimu).then((res) => {
          console.log(res);
          this.optionss = res.data;
        });
      },
      //删除
      handleDelete(index, row) {
        // console.log(row);
        ElMessageBox.confirm("是否删除此管理员", {
          confirmButtonText: "OK",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            let deletes = {
              _gp: "admin.advert",
              _mt: "delete",
              type: row.type,
              adId: row.id,
            };
            http.post(deletes).then((res) => {
              console.log(res);
              if (200 == res.errno) {
                this.tableData.splice(index, 1);
              }
            });
            ElMessage({
              type: "success",
              message: "删除成功",
            });
          })
          .catch(() => {
            ElMessage({
              type: "info",
              message: "取消成功",
            });
          });
      },
      //编辑
      aikes(){
          this.$nextTick(()=>{
            this.$refs.ruleFormRef.clearValidate()
          })
      },
      handleEdit(row) {
        this.adId = row.id;
        this.category();
        this.dows();
        console.log(row);
        this.dialogVisibles = true;
        Object.assign(this.ruleForms, row);
        if (Number(this.ruleForms.unionValue)) {
          this.ruleForms.unionValue = Number(this.ruleForms.unionValue);
        }
      },
      //修改
      editor(ruleFormRefs) {
        this.$refs[ruleFormRefs].validate((valid) => {
          if (valid) {
                let dinen = {
              _gp: "admin.advert",
              _mt: "edit",
              adId: this.adId,
              title: this.ruleForms.title,
              imgUrl: this.ruleForms.imgUrl,
              status: this.ruleForms.status,
              unionValue: this.ruleForms.unionValue,
              type: this.ruleForms.type,
              unionType: this.ruleForms.unionType,
            };
            http.post(dinen).then((res) => {
              console.log(res);
              if (200 == res.errno) {
            ElMessage.success("修改成功！");
            this.advertising();
            this.dialogVisibles = false;
          } else {
            ElMessage.error("修改失败！");
          }
        });
          } else {
            console.log('error submit!!');
            return false;
          }
        });   
      },
      //商品树
      dows() {
        let dows = {
          _gp: "admin.product",
          _mt: "getSpuBigTree",
        };
        http.post(dows).then((res) => {
          this.options = res.data;
        });
      },
      
      //获取图片
      handleAvatarSuccess(res) {
        console.log(res);
        if (200 == res.errno) {
          this.ruleForm.imgUrl = res.url;
        }
      },
      //点击添加弹出框显示
      AvatarSuccess(res) {
        this.dialogVisibles = true;
        if (200 == res.errno) {
          this.ruleForms.imgUrl = res.url;
        }
       
      },
      //广告类型
      advertisingtype(item) {
        for (const i of this.adTypeMap) {
          if (item.type == i.value) {
            return i.name;
          }
        }
      },
      add(){
        this.dialogVisible = true
      },
      //对话框的确认按钮
      sure(ruleFormRef) {
        this.$refs[ruleFormRef].validate((valid) => {
          if (valid) {
            if(this.ruleForm.imgUrl==''){
              this.ruleForm.imgUrl = "//www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png"
            }
            let sas = {
              _gp: "admin.advert",
              _mt: "create",
              type: this.ruleForm.type,
              unionType: this.ruleForm.unionType,
              title: this.ruleForm.title,
              unionValue: this.ruleForm.unionValue,
              imgUrl: this.ruleForm.imgUrl,
              status: this.ruleForm.status,
            };
            
            http.post(sas).then((res) => {
          console.log(res);
          if (200 == res.errno) {
            ElMessage.success("添加成功！");
            this.dialogVisible = false;
             this.ruleForm = this.$options.data().ruleForm;
            this.advertising();
          }
        });
          } else {
            ElMessage.error("添加失败")
            return false;
          }
        });
      },
      
      show(row) {
        for (const i of this.adUnionTypeMap) {
          if (row.unionType == i.value) return i.name;
        }
      },
      //时间戳
      dateFormat(row, column) {
        var date = row[column.property];
        if (date == undefined) {
          return "无";
        }
        return moment(date).format("MM月DD日HH时mm分");
      },
      //分页
      handleSizeChange(val) {
        this.paging.limit = val;
        this.advertising();
      },
      handleCurrentChange(val) {
        this.paging.page = val;
        this.advertising();
      },
    },
  };
</script>
<style scoped>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
</style>
